<template>
  <page-meta :page-style="$theme.pageStyle"></page-meta>
  <scroll-view @scroll="scrollPosition" :scroll-into-view="theItem" :style="{height: '88vh'}" :scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true" >
    <view class="body-content">
      <view class="page-list">
        <view v-if="isShowLoad" class="py-[30rpx]">
          <u-loadmore :status="loadMore" />
        </view>
        <view :id="`theItem-${newsIndex}`" v-for="(newsItem, newsIndex) in dataList" :key="newsIndex">
          <!--          <view class="page-time">-->
          <!--            {{ newsItem.timeData }}-->
          <!--          </view>-->
          <view class="list-child" v-if="newsItem.direction == 'left'">
            <image class="child-pic" :src="newsItem.user_info.avatar" mode="aspectFit"></image>
            <view class="mx-[10rpx]">
              <view class="child-time">
                {{ newsItem.user_info.nickname }} {{ newsItem.timeData }}
              </view>
              <view class="child-text">
                {{ newsItem.content }}
              </view>
            </view>
          </view>
          <view class="list-child list-childMy" v-if="newsItem.direction == 'right'">
            <view class="mx-[20rpx]">
              <view class="child-time">
                {{ newsItem.timeData }}
              </view>
              <view class="child-text">
                {{ newsItem.content }}
              </view>
            </view>
            <image class="child-pic" :src="newsItem.user_info.avatar" mode="aspectFit"></image>
          </view>
        </view>
      </view>
    </view>
  </scroll-view>
  <view class="page-bottom">
    <input type="text" v-model="msgFormData.content" placeholder="输入您想说的内容" class="bottom-input">
    <view class="bottom-btn" @click="sendMsg">
      发送
    </view>
  </view>
</template>
<script lang="ts" setup>
import {reactive, ref, shallowRef,watch,nextTick} from "vue"
import {onLoad, onShow, onPullDownRefresh, onHide, onUnload} from "@dcloudio/uni-app";
import {getChatGroupListApi, getChatListApi} from "@/api/new";
import {storeToRefs} from "pinia";
import {useUserStore} from "@/stores/user";
import {getToken} from "@/utils/auth";

const isShowLoad = ref(true)
const dataList = ref([])
const page_no_ffy = ref(1);
const getChatList = async () => {
  loadMore.value = 'loading'
  isShowLoad.value = true
  const {lists} = await getChatListApi({
    group_id: optionsInfo.value.group_id,
    page_no: page_no_ffy.value,
    page_size: 8
  })
  if(page_no_ffy.value == 1){
    dataList.value = lists;
    theItem.value = "theItem-" + (dataList.value.length - 1)
    isShowLoad.value = false
  }else{
    let laoDataList = JSON.parse(JSON.stringify(dataList.value))
    let xinDataList = lists.concat(laoDataList);
    dataList.value = xinDataList;
    scrollTop.value = 100
  }
  page_no_ffy.value++
  if (lists.length == 0) {
    loadMore.value = 'normal'
  }
}

const loadMore = ref('loading')
const theItem = ref()

const scrollTop = ref(0)//滚动条位置

const scrollPosition = (e:any) => {
  if(e.detail.scrollTop < 5){
    getChatList()
  }
}

let msgFormData = ref() as any
let optionsInfo = ref() as any

onLoad((options) => {
  optionsInfo.value = options
  msgFormData.value = {
    type: "sendInfo",
    info_type: "word",
    goal_user_id: optionsInfo.value.goal_user_id,
    content: ''
  }
})

const getMsg = () => {
  uni.closeSocket();
  //设置屏幕保持常亮不灭
  uni.setKeepScreenOn({
    keepScreenOn: true
  });
  const token = getToken()
  uni.connectSocket({
    url: 'wss://qxyhj.ybkj.club/wss',
    header: {
      'content-type': 'application/json',
      'token': token,
    },
    method: 'GET',
    success() {
      uni.onSocketOpen(function (res) {
        console.log('WebSocket连接已打开！');
        uni.sendSocketMessage({
          data: 'wo'
        });
        uni.onSocketMessage(function (res) {
          const data:any = JSON.parse(res.data)
          if (data.type == 'Info') {
            console.log('JSON.parse(res.data)====', JSON.parse(res.data));
            console.log('data.data===>',data.data)
            // let laoDataList = JSON.parse(JSON.stringify(dataList.value))
            dataList.value.push(data.data)
            theItem.value = "theItem-" + (dataList.value.length - 1)
            // let xinDataList = laoDataList.push(data.data);
            // dataList.value = xinDataList;
          }
        });
      });
      uni.onSocketError(function (res) {
        console.log('WebSocket连接打开失败，请检查！');
      });
    }
  });
}

onShow(() => {
  getMsg()
  getChatList()
})

onUnload(() => {
  uni.closeSocket();
  uni.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！');
  });
})


const userStore = useUserStore()
const {userInfo, isLogin} = storeToRefs(userStore)
// console.log('userInfo',JSON.parse(JSON.stringify(userInfo))._object.userInfo.avatar)

const sendMsg = () => {
  uni.sendSocketMessage({
    data: JSON.stringify(msgFormData.value),
    async success(res) {
      console.log('res', res)
      msgFormData.value.content = ''
    },
    fail(err) {
      console.log('err', err)
    }
  });
}

</script>
<style lang="scss">
page {
  background-color: #F0F7FF;
}
</style>
<style scoped lang="scss">
.page-time {
  font-size: 24rpx;
  color: #999999;
  padding: 30rpx;
  text-align: center;
}

.page-list {
  width: 100%;
  padding: 30rpx 0;

  .list-child {
    padding: 0 30rpx;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    margin-bottom: 30rpx;

    .child-pic {
      width: 90rpx;
      height: 90rpx;
      border-radius: 50%;
    }

    .child-text {
      background-color: #FFFFFF;
      font-size: 30rpx;
      color: #111111;
      padding: 30rpx;
      border-radius: 0 20rpx 20rpx 20rpx;
      margin: 0 10rpx;
      display: inline-block;
    }

    .child-time {
      font-size: 24rpx;
      margin-bottom: 10rpx;
      color: #999999;
      text-align: left;
    }

    &My {
      justify-content: flex-end;

      .child-text {
        background-color: var(--color-primary);
        border-radius: 20rpx 0 20rpx 20rpx;
        color: #ffffff;
      }

      .child-time {
        text-align: right;
      }
    }
  }
}

.page-bottom {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 30rpx 30rpx calc(60rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;
  //position: fixed;
  //bottom: 0;

  .bottom-input {
    width: 100%;
    margin-right: 20rpx;
    height: 80rpx;
    background-color: #F6FAFF;
    color: #111111;
    border-radius: 40rpx;
    padding: 0 20rpx;
  }

  .bottom-btn {
    flex-shrink: 0;
    padding: 10rpx 20rpx;
    border-radius: 30rpx;
    background-image: linear-gradient(to right, var(--color-primary), var(--color-minor));
    color: #fff;
    font-size: 28rpx;
  }

  &Footer {
    height: calc(140rpx + env(safe-area-inset-bottom));
  }
}
</style>